import { getScheduleList } from '@/api'

export const useScheduleStore = defineStore('schedule', {
  state: () => ({
    // 排期缓存
    caches: {} as Record<string, ISchedule[] | undefined>
  }),

  actions: {
    /**
     * 请求排期数据
     */
    async fetchScheduleList(cinemaId: number, filmId: number, date: number) {
      // 按照规则拼接 key
      const key = [cinemaId, filmId, date].join(':')

      // 获取缓存中的值
      const value = this.caches[key]

      // 判断
      if (value) {
        // 如果有缓存，则直接返回
        return value
      } else {
        // 没有缓存，则调用接口
        const { schedules } = await getScheduleList(cinemaId, filmId, date)

        // 写入缓存
        this.caches[key] = schedules

        return schedules
      }
    }
  }
})
